module.exports = (vm) => {
  uni.$u.http.setConfig((config) => {
    config.baseURL = 'https://cuui.cn';
    return config
  })

  // 请求列队
  let requestList = [];
  // 是否正在刷新Token
  let isRefreshToken = false;

  // 请求拦截
  uni.$u.http.interceptors.request.use((config) => {
    config.data = config.data || {}
    config.header.Authorization = vm.$store.state.token ? vm.$store.state.token.token : null
    return config
  }, config => {
    return Promise.reject(config);
  })

  // 响应拦截
  uni.$u.http.interceptors.response.use((response) => {
    const { data } = response;
    return data === undefined ? {} : data;
  }, async (response) => {
    if (response.statusCode === 401) {
      if (!isRefreshToken) {
        isRefreshToken = true;
        const refreshToken = vm.$store.state.token ? vm.$store.state.token.refreshToken : null;
        if (!refreshToken) {
          return Authorized(response.data);
        }
        try {
          const { code, data } = await uni.$u.http.post('/api/app/user/refreshToken', { refreshToken });
          if (code !== 1000) {
            return Authorized(response.data);
          }
          vm.$store.commit('MLOGIN', data);
          requestList.forEach(cb => cb());
          return new Promise(resolve => {
            resolve(uni.$u.http.request(response.config));
          });
        } catch (e) {
          requestList.forEach(cb => cb());
          return Authorized(response.data);
        } finally {
          requestList = [];
          isRefreshToken = false;
        }
      } else {
        return new Promise(resolve => {
          requestList.push(() => {
            resolve(uni.$u.http.request(response.config));
          });
        });
      }
    }
    uni.showToast({ title: '服务器异常~', duration: 10000, icon: 'none' });
    return Promise.reject(response);
  });

  // 处理认证
  function Authorized(data) {
    uni.showModal({
      title: '系统提示',
      content: '登录已过期，请重新登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    })
    return Promise.reject(data)
  }
}